package com.cloud.bc.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HtmlUtil;
import com.cloud.bc.model.entity.BcChats;
import com.cloud.bc.mapper.BcChatsMapper;
import com.cloud.bc.model.entity.BcNotices;
import com.cloud.bc.model.entity.BcSingleContacts;
import com.cloud.bc.model.entity.BcSingles;
import com.cloud.bc.model.request.ChatRequest;
import com.cloud.bc.model.response.RecentChatResponse;
import com.cloud.bc.service.BcChatsService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.bc.service.BcSinglesService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 聊天
 *
 * @author douhaichao code generator
 * @date 2021-01-12 11:57:16
 */
@Service
@AllArgsConstructor
public class BcChatsServiceImpl extends ServiceImpl<BcChatsMapper, BcChats> implements BcChatsService {
    private final BcSinglesService bcSinglesService;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcChats selectOne(BcChats req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcChats>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcChats> selectAll(BcChats req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcChats> selectPage(Page page, BcChats req) {
        IPage<BcChats> list = baseMapper.selectPage(
                page,
                new QueryWrapper<BcChats>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<BcChats> selectPageByLike(Page page, BcChats req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getId()) {
            queryWrapper.eq("id", req.getId());
        }

        if (null != req.getUserId()) {
            queryWrapper.eq("user_id", req.getUserId());
        }

        if (null != req.getTargetId()) {
            queryWrapper.eq("target_id", req.getTargetId());
        }

        if (!StrUtil.isEmpty(req.getUidpid())) {
            queryWrapper.like("uidpid", req.getUidpid());
        }

        if (null != req.getWordType()) {
            queryWrapper.eq("word_type", req.getWordType());
        }

        if (!StrUtil.isEmpty(req.getWords())) {
            queryWrapper.like("words", req.getWords());
        }

        if (null != req.getIsLook()) {
            queryWrapper.eq("is_look", req.getIsLook());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }
        IPage<BcChats> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcChats req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public List<RecentChatResponse> selectRecentChat(Page page, Integer userId) {
        List<RecentChatResponse> recentChatResponses = baseMapper.selectRecentChat(page, userId);
        List<RecentChatResponse> listNew = new ArrayList<>();
        for (RecentChatResponse item : recentChatResponses) {
            Integer uId = Convert.toInt(item.getUserId(), 0);
            Integer targetId = Convert.toInt(item.getTargetId(), 0);
            if (uId.equals(-1) || targetId.equals(-1) || targetId.equals(0)) {
                //过滤系统消息，在sql里过滤太慢了
                continue;
            }
            if (uId == userId) {
                //如果UID是自己，就把目标ID给到userid
                item.setUserId(targetId);
            }
            if (listNew.stream().filter(t -> t.getUserId().equals(item.getUserId())).count() == 0) {
                //过滤重复数据
                listNew.add(item);
            }
        }
//        赋值消息
        Set<Integer> msgIdList = listNew.stream().map(t -> t.getMsgId()).collect(Collectors.toSet());
        if (msgIdList.size() > 0) {
            List<BcChats> bcChats = baseMapper.selectBatchIds(msgIdList);
            listNew.forEach(item -> {
                BcChats bcChatsResult =
                        bcChats.stream().filter(t -> t.getId().equals(item.getMsgId())).
                                findFirst().orElse(new BcChats());
                item.setMsgTitle(HtmlUtil.cleanHtmlTag(bcChatsResult.getWords()));
            });
        }
        //赋值消息
//赋值用户
        Set<Integer> userIdList = listNew.stream().map(t -> t.getUserId()).collect(Collectors.toSet());
        if (userIdList.size() > 0) {

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("user_id", userIdList);
            List<BcSingles> list = bcSinglesService.list(queryWrapper);
            listNew.forEach(item -> {
                BcSingles bcSingles = list.stream().filter(t -> t.getUserId().equals(item.getUserId())).findFirst().orElse(new BcSingles());
                item.setNickname(bcSingles.getNickname());
                item.setPhoto(bcSingles.getPhoto());
                //查询未读消息,这里要查询别人给我发的未读数量
                QueryWrapper queryWrapperUnReadCount = new QueryWrapper();
                queryWrapperUnReadCount.eq("user_id", item.getUserId());
                queryWrapperUnReadCount.eq("target_id", userId);
                queryWrapperUnReadCount.eq("is_look", 0);
                Integer count = baseMapper.selectCount(queryWrapperUnReadCount);
                item.setUnreadNum(count);
            });
            //赋值用户
        }
        return listNew;
    }

    @Override
    public List<BcNotices> selectChatList(ChatRequest req) {
        List<BcNotices> bcNotices = baseMapper.selectChatList(req);
//查询出未读ID，变更为已读
        Set<BcNotices> collect = bcNotices.stream().filter(t -> t.getIsLook().equals(0)).collect(Collectors.toSet());
        //查出当前用户未读消息
        Set<Integer> readList = collect.stream().filter(t -> t.getTargetId().equals(req.getUserId()))
                .map(t -> t.getId()).collect(Collectors.toSet());
        if (null != readList && readList.size() > 0) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("id", readList);
            BcChats bcChats = new BcChats();
            bcChats.setIsLook(1);
            baseMapper.update(bcChats, queryWrapper);
        }
        return bcNotices;
    }

    //删除聊天记录
    @Override
    public void delete(BcChats req) {
        baseMapper.deleteRecord(req);
    }
}
